import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList, StyleSheet } from 'react-native';
import { useRoute, useNavigation } from '@react-navigation/native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { useSelector } from 'react-redux';
import { initSocket } from '../../../services/socket';
import { MessageStorage } from '../../../services/messageStorage';

interface Message {
  id: string;
  senderId: string;
  receiverId: string;
  content: string;
  timestamp: number;
  status: 'sent' | 'delivered' | 'read';
}

const ChatRoom = () => {
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputMessage, setInputMessage] = useState('');
  const [socket, setSocket] = useState<WebSocket | null>(null);
  const route = useRoute();
  const navigation = useNavigation();
  const userInfo = useSelector((state: any) => state.auth.userInfo);
  const { friendId, friendName } = route.params as { friendId: string; friendName: string };

  useEffect(() => {
    // 加载历史消息
    const loadHistoryMessages = async () => {
      if (userInfo?._id) {
        const historyMessages = await MessageStorage.getMessages(userInfo._id, friendId);
        setMessages(historyMessages.reverse()); // 反转消息列表以显示最新消息在底部
      }
    };
    loadHistoryMessages();

    // 设置导航标题
    navigation.setOptions({
      headerTitle: friendName,
      headerLeft: () => (
        <TouchableOpacity 
          style={styles.headerButton} 
          onPress={() => navigation.goBack()}
        >
          <MaterialIcons name="arrow-back" size={24} color="#333" />
        </TouchableOpacity>
      ),
    });

    // 初始化WebSocket连接
    if (userInfo?._id) {
      const ws = initSocket(userInfo._id);
      setSocket(ws);

      ws.onmessage = async (event) => {
        const message = JSON.parse(event.data);
        if (message.type === 'chat' && 
            ((message.senderId === friendId && message.receiverId === userInfo._id) ||
             (message.senderId === userInfo._id && message.receiverId === friendId))) {
          // 先更新UI，确保消息立即显示
          setMessages(prevMessages => [message, ...prevMessages]);
          // 异步保存到本地存储
          MessageStorage.addMessage(message).catch(error => {
            console.error('保存消息到本地存储失败:', error);
          });
        }
      };

      return () => {
        if (ws) {
          ws.close();
        }
      };
    }
  }, [userInfo?._id, friendId, friendName]);

  const handleSendMessage = () => {
    if (!inputMessage.trim() || !userInfo?._id) return;
    
    // 检查WebSocket连接状态
    if (!socket || socket.readyState !== WebSocket.OPEN) {
      console.log('WebSocket连接已断开，正在重新连接...');
      const ws = initSocket(userInfo._id);
      setSocket(ws);
      return;
    }

    const message = {
      type: 'chat',
      id: Date.now().toString(),
      senderId: userInfo._id,
      receiverId: friendId,
      content: inputMessage.trim(),
      timestamp: Date.now(),
      status: 'sent' as const
    };

    socket.send(JSON.stringify(message));
    // 保存发送的消息到本地存储
    MessageStorage.addMessage(message);
    setMessages(prevMessages => [message, ...prevMessages]);
    setInputMessage('');
  };

  const renderMessage = ({ item }: { item: Message }) => {
    const isSentByMe = item.senderId === userInfo?._id;

    return (
      <View style={[styles.messageContainer, isSentByMe ? styles.sentMessage : styles.receivedMessage]}>
        <View style={[styles.messageBubble, isSentByMe ? styles.sentBubble : styles.receivedBubble]}>
          <Text style={styles.messageText}>{item.content}</Text>
          <Text style={styles.messageTime}>
            {new Date(item.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
          </Text>
        </View>
      </View>
    );
  };

  return (
    <View style={styles.container}>
      <FlatList
        data={messages}
        renderItem={renderMessage}
        keyExtractor={item => item.id}
        contentContainerStyle={styles.messagesList}
        inverted
      />
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          value={inputMessage}
          onChangeText={setInputMessage}
          placeholder="输入消息..."
          multiline
        />
        <TouchableOpacity 
          style={styles.sendButton} 
          onPress={handleSendMessage}
          disabled={!inputMessage.trim()}
        >
          <MaterialIcons 
            name="send" 
            size={24} 
            color={inputMessage.trim() ? "#4A90E2" : "#999"} 
          />
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
  },
  headerButton: {
    marginLeft: 10,
  },
  messagesList: {
    paddingHorizontal: 16,
    paddingVertical: 8,
  },
  messageContainer: {
    marginVertical: 4,
    maxWidth: '80%',
  },
  sentMessage: {
    alignSelf: 'flex-end',
  },
  receivedMessage: {
    alignSelf: 'flex-start',
  },
  messageBubble: {
    borderRadius: 16,
    padding: 12,
    maxWidth: '100%',
  },
  sentBubble: {
    backgroundColor: '#4A90E2',
  },
  receivedBubble: {
    backgroundColor: '#FFFFFF',
  },
  messageText: {
    fontSize: 16,
    color: '#333333',
  },
  messageTime: {
    fontSize: 12,
    color: '#999999',
    marginTop: 4,
    alignSelf: 'flex-end',
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 8,
    backgroundColor: '#FFFFFF',
    borderTopWidth: 1,
    borderTopColor: '#EEEEEE',
  },
  input: {
    flex: 1,
    minHeight: 40,
    maxHeight: 100,
    backgroundColor: '#F5F5F5',
    borderRadius: 20,
    paddingHorizontal: 16,
    paddingVertical: 8,
    marginRight: 8,
    fontSize: 16,
  },
  sendButton: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default ChatRoom;